package handlers

import (
	"net/http"
	"ota-backend/config"
	"ota-backend/models"

	"github.com/gin-gonic/gin"
)

// TaskHandler 任务处理器
type TaskHandler struct{}

// NewTaskHandler 创建任务处理器
func NewTaskHandler() *TaskHandler {
	return &TaskHandler{}
}

// CreateTask 创建任务
func (h *TaskHandler) CreateTask(c *gin.Context) {
	var task models.Task
	if err := c.ShouldBindJSON(&task); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查产品是否存在
	var product models.Product
	if err := config.DB.First(&product, "id = ?", task.ProductID).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "产品不存在"})
		return
	}

	// 检查固件版本是否存在
	var firmware models.Firmware
	if err := config.DB.Where("product_id = ? AND version = ?", task.ProductID, task.Version).First(&firmware).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "固件版本不存在"})
		return
	}

	// 如果指定了SN，检查设备是否存在
	// if task.SN != "" {
	// 	var device models.Device
	// 	if err := config.DB.Where("sn = ? AND product_id = ?", task.SN, task.ProductID).First(&device).Error; err != nil {
	// 		c.JSON(http.StatusBadRequest, gin.H{"error": "设备不存在"})
	// 		return
	// 	}
	// }

	if err := config.DB.Create(&task).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, task)
}

// GetTasks 获取任务列表
func (h *TaskHandler) GetTasks(c *gin.Context) {
	productID := c.Query("product_id")
	status := c.Query("status")

	var tasks []models.Task
	query := config.DB.Preload("Product")

	if productID != "" {
		query = query.Where("product_id = ?", productID)
	}

	if status != "" {
		query = query.Where("status = ?", status)
	}

	if err := query.Order("created_at DESC").Find(&tasks).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, tasks)
}

// GetTask 获取单个任务
func (h *TaskHandler) GetTask(c *gin.Context) {
	id := c.Param("id")

	var task models.Task
	if err := config.DB.Preload("Product").First(&task, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "任务不存在"})
		return
	}

	c.JSON(http.StatusOK, task)
}

// UpdateTask 更新任务
func (h *TaskHandler) UpdateTask(c *gin.Context) {
	id := c.Param("id")

	var task models.Task
	if err := config.DB.First(&task, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "任务不存在"})
		return
	}

	var updateData models.Task
	if err := c.ShouldBindJSON(&updateData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 如果更新了产品ID，检查产品是否存在
	if updateData.ProductID != "" && updateData.ProductID != task.ProductID {
		var product models.Product
		if err := config.DB.First(&product, "id = ?", updateData.ProductID).Error; err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "产品不存在"})
			return
		}
	}

	// 如果更新了版本，检查固件是否存在
	if updateData.Version != "" && (updateData.Version != task.Version || updateData.ProductID != task.ProductID) {
		productID := updateData.ProductID
		if productID == "" {
			productID = task.ProductID
		}
		var firmware models.Firmware
		if err := config.DB.Where("product_id = ? AND version = ?", productID, updateData.Version).First(&firmware).Error; err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "固件版本不存在"})
			return
		}
	}

	if err := config.DB.Model(&task).Updates(updateData).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, task)
}

// DeleteTask 删除任务
func (h *TaskHandler) DeleteTask(c *gin.Context) {
	id := c.Param("id")

	var task models.Task
	if err := config.DB.First(&task, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "任务不存在"})
		return
	}

	if err := config.DB.Delete(&task).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "任务删除成功"})
}
